import sysConfig from "@/config";
import tool from "@/utils/tool";
import { createI18n } from "vue-i18n";
// import el_zh_cn from "element-plus/lib/locale/lang/zh-cn";
import el_zh_cn from "element-plus/es/locale/lang/zh-cn";
import el_en from "element-plus/es/locale/lang/en";
// import el_en from "element-plus/lib/locale/lang/en";
import store from "@/store/index";
import common from "@/api/model/common.js";

import zh_cn from "./lang/zh-cn.js";
import en from "./lang/en.js";

const messages = {
	zh_CN: {
		el: el_zh_cn,
		...zh_cn,
	},
	en_US: {
		el: el_en,
		...en,
	},
};
const i18n = createI18n({
	locale: tool.data.get("APP_LANG") || sysConfig.LANG,
	fallbackLocale: "zh_CN",
	globalInjection: true,
	silentTranslationWarn: true,
	legacy: false,
	messages,
});
const loadedLanguages = [];
function setI18nLanguage(lang) {
	i18n.global.locale = lang;
	document.querySelector("html").setAttribute("lang", lang);
	localStorage.setItem("i18n", lang);
	return lang;
}
//加载多语言
function loadLanguageAsync(lang) {
	let locale = store.state.common.locale;
	store.dispatch("common/setLocale", lang);
	if (loadedLanguages.includes(lang)) {
		if (i18n.locale !== lang) setI18nLanguage(lang);
		return Promise.resolve();
	}

	return common.getI18nData
		.get(lang)
		.then((response) => {
			let defaultI18n = {};
			if (lang === "zh_CN") {
				defaultI18n = {
					el: el_zh_cn,
					...zh_cn,
				};
			} else {
				defaultI18n = {
					el: el_en,
					...en,
				};
			}
			const msgs = Object.assign(response.data, defaultI18n);
			store.dispatch("common/setRequestI18n", response.data);
			loadedLanguages.push(lang);
			i18n.global.setLocaleMessage(lang, msgs);
			return setI18nLanguage(lang);
		})
		.catch(() => {
			store.dispatch("common/setLocale", locale);
		});
}
loadLanguageAsync(tool.data.get("APP_LANG") || "zh_CN");
i18n.loadLanguageAsync = loadLanguageAsync;
export default i18n;
